package com.java.gulimall.search.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.java.common.to.es.SkuEsModel;
import com.java.common.utils.R;
import com.java.gulimall.search.constant.ElasticConstant;
import com.java.gulimall.search.feign.ProductFeignService;
import com.java.gulimall.search.vo.AttrResponseVo;
import com.java.gulimall.search.vo.SearchParam;
import com.java.gulimall.search.vo.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author jl
 * Created on 2020/7/12
 */
@Service
public class MallSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ProductFeignService productFeignService;

    public SearchResult search(SearchParam searchParam) {
        SearchResult result = new SearchResult();

        // 构建查询条件
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        String s = searchRequest.source().toString();
//        System.err.println(s);
        try {
            // 执行检索
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            // 解析结果,封装返回
            result = buildSearchResult(searchResponse,searchParam);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;

    }

    private SearchResult buildSearchResult(SearchResponse searchResponse,SearchParam searchParam) {
        SearchResult result = new SearchResult();
        // 封装商品集合
        SearchHits hits = searchResponse.getHits();
        SearchHit[] hitsHits = hits.getHits();
        List<SkuEsModel> products = new ArrayList<>();
        for (SearchHit hit : hitsHits) {
            String sourceAsString = hit.getSourceAsString();
            SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
            if (StringUtils.isNotBlank(searchParam.getKeyword())) {
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField skuTitle = highlightFields.get("skuTitle");
                String s = skuTitle.getFragments()[0].toString();
                skuEsModel.setSkuTitle(s);
            }
            products.add(skuEsModel);
        }
        result.setProduct(products);

        Aggregations aggregations = searchResponse.getAggregations();
        // 解析分类聚合
        ParsedLongTerms catalogAgg = aggregations.get("catalogAgg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            String key = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.valueOf(key));
            // name在子聚合中
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalogNameAgg");
            // 一个id只会有一个聚合结果
            String categoryName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(categoryName);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        // 解析品牌聚合
        ParsedLongTerms brandAgg = aggregations.get("brandAgg");
        List<SearchResult.BrandVo> brands = new ArrayList<>();
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            String key = bucket.getKeyAsString();
            brandVo.setBrandId(Long.valueOf(key));
            // 解析子聚合
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brandNameAgg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brandImgAgg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            brands.add(brandVo);
        }
        result.setBrands(brands);

        // 解析属性聚合
        List<SearchResult.AttrVo> attrs =new ArrayList<>();
        ParsedNested attrAgg = aggregations.get("attrAgg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attrIdAgg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            String key = bucket.getKeyAsString();
            attrVo.setAttrId(Long.valueOf(key));
            // 解析子聚合,设置attrName
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attrNameAgg");
            attrVo.setAttrName(attrNameAgg.getBuckets().get(0).getKeyAsString());
            // 解析子聚合,循环设置attrName attrValue
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attrValueAgg");
            List<String> attrValues = new ArrayList<>();
            for (Terms.Bucket valueAggBucket : attrValueAgg.getBuckets()) {
                attrValues.add(valueAggBucket.getKeyAsString());
            }
            attrVo.setAttrValue(attrValues);
            attrs.add(attrVo);
        }

        result.setAttrs(attrs);

        // 分页信息-总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        // 总页数
        int totalPage = (int) (total % ElasticConstant.PRODUCT_PAGE_SIZE == 0 ? total / ElasticConstant.PRODUCT_PAGE_SIZE : (total / ElasticConstant.PRODUCT_PAGE_SIZE + 1));
        result.setTotalPages(totalPage);
        // 当前页
        result.setPageNum(searchParam.getPageNum());
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        //6、构建面包屑导航
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {
            List<SearchResult.NavVo> collect = searchParam.getAttrs().stream().map(attr -> {
                //1、分析每一个attrs传过来的参数值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                result.getAttrIds().add(Long.valueOf(Long.parseLong(s[0])));
                if (r.getCode() == 0) {
                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }

                //2、取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
                //拿到所有的查询条件，去掉当前条件
                String replace = replaceQueryString(searchParam, attr,"attrs");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);

                return navVo;
            }).collect(Collectors.toList());

            result.setNavs(collect);
        }
        // 品牌,分类
        if(!CollectionUtils.isEmpty(searchParam.getBrandId())){
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo vo = new SearchResult.NavVo();
            vo.setNavName("品牌");
            R r = productFeignService.brandInfos(searchParam.getBrandId());
            if (r.getCode() == 0) {
                List<SearchResult.BrandVo> brandVos = r.getData(new TypeReference<List<SearchResult.BrandVo>>() {
                });
                StringBuilder sb = new StringBuilder();
                String replace = "";
                for (SearchResult.BrandVo brandVo : brandVos) {
                    sb.append(brandVo.getBrandName()+";");
                    replace = replaceQueryString(searchParam, String.valueOf(brandVo.getBrandId()),"brandId");
                }
                vo.setNavValue(sb.toString());
                vo.setLink("http://search.gulimall.com/list.html?" + replace);
            }
            navs.add(vo);
        }
        return result;
    }

    private String replaceQueryString(SearchParam searchParam, String queryString, String key) {
        String encode = "";
        try {
            encode = URLEncoder.encode(queryString,"UTF-8");
            encode = encode.replace("+","%20");  //浏览器对空格的编码和Java不一样，差异化处理
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return searchParam.get_queryString().replace("&"+key+"=" + encode, "");
    }

    /**
     * 构建检索条件
     * 全文匹配, 过滤(按照品牌,分类,属性,价格区间,库存), 排序, 分页, 高亮, 聚合分析
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 构建DSL语句
        // 全文匹配, 过滤(按照品牌,分类,属性,价格区间,库存)
        // 1.构建bool查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1.1 must - 全文检索
        if (StringUtils.isNotBlank(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        // 1.2 filter - 过滤
        // 三级分类
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        // 品牌
        if (!CollectionUtils.isEmpty(param.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        // 属性  一个属性对应一个nested查询
        if (!CollectionUtils.isEmpty(param.getAttrs())) {
            // attrs=1_5寸:8寸&attrs=2_8G:16G
            for (String attrStr : param.getAttrs()) {
                // attrs=1_5寸:8寸
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String attrId = s[0]; // 检索的属性id
                String[] attrValues = s[1].split(":"); // 检索属性的值
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }

        // 库存
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        // 价格区间
        if (StringUtils.isNotBlank(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            // 1_500/_500/500_
            String[] prices = param.getSkuPrice().split("_");
            if (prices.length == 2) {
                rangeQuery.from(prices[0]).to(prices[1]);
            } else if (prices.length == 1) {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.to(prices[0]);
                }
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.from(prices[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }


        sourceBuilder.query(boolQuery);
        // 排序, 分页, 高亮
        if (StringUtils.isNotBlank(param.getSort())) {
            String[] s = param.getSort().split("_");
            SortOrder sortOrder = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], sortOrder);
        }
        sourceBuilder.from((param.getPageNum() - 1) * ElasticConstant.PRODUCT_PAGE_SIZE);
        sourceBuilder.size(ElasticConstant.PRODUCT_PAGE_SIZE);
        if (StringUtils.isNotBlank(param.getKeyword())) {
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }

        // 聚合分析
        // 品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg");
        brandAgg.field("brandId").size(50);
        // 品牌聚合的子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brandNameAgg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brandImgAgg").field("brandImg").size(1));
        sourceBuilder.aggregation(brandAgg);

        // 分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalogAgg").field("catalogId").size(50);
        // 分类聚合的子聚合
        catalogAgg.subAggregation(AggregationBuilders.terms("catalogNameAgg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalogAgg);

        // 属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attrAgg", "attrs");
        // 聚合分析出当前attrId
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId").size(50);
        // 聚合分析出当前attrId对应的名字
        attrIdAgg.subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName").size(1));
        // 聚合分析出当前attrId对应的所有的属性值
        attrIdAgg.subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue").size(50));
        attrAgg.subAggregation(attrIdAgg);
        sourceBuilder.aggregation(attrAgg);


        SearchRequest searchRequest = new SearchRequest(new String[]{ElasticConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }
}
